<template>
  <div :class="[prefixCls, { fullscreen }]">
    <a-upload name="file" :customRequest="uploadFile" :showUploadList="false" accept="image/*">
      <a-button :loading="loading" type="primary" v-bind="{ ...getButtonProps }">
        {{ t('component.upload.imgUpload') }}
      </a-button>
    </a-upload>
  </div>
</template>
<script lang="ts">
export default {
  name: 'TinymceImageUpload',
};
</script>
<script setup lang="ts">
import { computed, ref } from 'vue';

import { useDesign } from '/@/hooks/web/useDesign';
import { useI18n } from '/@/hooks/web/useI18n';

import { uploadTinymce, downLoadTinymceApi } from '/@/api/sys/upload';

const props = defineProps({
  fullscreen: {
    type: Boolean,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(['uploading', 'done', 'error']);

let loading = ref(false);

const { t } = useI18n();
const { prefixCls } = useDesign('tinymce-img-upload');

const getButtonProps = computed(() => {
  const { disabled } = props;
  return {
    disabled,
  };
});
const uploadFile = async (info) => {
  loading.value = true;
  emit('uploading', info.name);
  try {
    const { data } = await uploadTinymce({ name: 'file', file: info.file });
    if (data.code == 200) {
      const url = downLoadTinymceApi + data.result.fileName;
      emit('done', info.name, url);
    } else {
      emit('error');
    }
  } finally {
    loading.value = false;
  }
};
</script>
<style lang="less" scoped>
@prefix-cls: ~'@{namespace}-tinymce-img-upload';

.@{prefix-cls} {
  position: absolute;
  top: 4px;
  right: 10px;
  z-index: 20;

  &.fullscreen {
    position: fixed;
    z-index: 10000;
  }
}
</style>
